package msgobj

import (
	"dev_gw/common"
	"dev_gw/device"
	mqttclient "dev_gw/mqttClient"
	"encoding/json"
	"fmt"
	"strings"
)

type AppSetMsgObject struct {
	_mqtt   *mqttclient.MqttClient
	_device *device.Device

	Tick int    `json:"tick"`
	Time int64  `json:"time"`
	Src  string `json:"src"`

	Ack struct {
		Tick int   `json:"tick"`
		Time int64 `json:"time"`
	} `json:"ack"`

	Dev []*setMsgObjectDev `json:"app"`

	dest string
}

func (r *AppSetMsgObject) ToJson() string {
	v, err := json.Marshal(r)
	if err != nil {
		fmt.Println("json marshal error, err is ", err)
		return ""
	}

	return string(v)
}

func NewAppSetMsgObject(m *mqttclient.MqttClient, d *device.Device) *AppSetMsgObject {
	return &AppSetMsgObject{
		_mqtt:   m,
		_device: d,
	}
}

func (d *AppSetMsgObject) Parse(topic, payload string) bool {
	result := strings.Split(topic, "/")
	if len(result) <= 4 {
		return false
	}

	d.dest = result[3]

	if (d.dest != "10000") && (d.dest != "dev_gw") {
		return false
	}

	err := json.Unmarshal([]byte(payload), d)
	if err != nil {
		fmt.Println("json unmarshal failed")
		return false
	}

	return true
}

func (d *AppSetMsgObject) Action() MsgInterface {
	for _, dev := range d.Dev {
		for _, point := range dev.Points {
			if !d._device.HasPoint(point.Key) {
				fmt.Println("can't find point, point name -->", point.Key)
				point.setError(1)
				continue
			}

			if d._device.WritePoint(point.Key, point.Val) {
				point.setError(0)
			} else {
				point.setError(1)
			}

		}
		// dev.SetStatus("online")
	}
	return d
}

func (d *AppSetMsgObject) Reply() bool {
	topic := "v1/app/" + d.dest + "/" + d.Src + "/point/set_ack"

	d.Ack.Tick = d.Tick
	d.Ack.Time = d.Time

	d.Src = common.ProcessName
	d._mqtt.Publish(topic, d.ToJson())

	return true
}
